﻿#include "cclient.h"

CClient::CClient() : m_socket(NULL)
{
    m_socket = new QLocalSocket();

    connect(m_socket, SIGNAL(connected()), SLOT(socketConnectedHandler()));
    connect(m_socket, SIGNAL(disconnected()), SLOT(socketDisConnectedHandler()));
    connect(m_socket, SIGNAL(error(QLocalSocket::LocalSocketError)), SLOT(socketErrorHandler(QLocalSocket::LocalSocketError)));
}

CClient::~CClient()
{
    m_socket->disconnectFromServer();
    delete m_socket;
}

void CClient::ConnectToServer(const QString &strServerName)
{
    // serverNewConnectionHandler 成员方法将被调用
    m_socket->connectToServer(strServerName);
    if (m_socket->waitForConnected())
    {
        // TODO:
    }
}

void CClient::sendMessage(const QString &msg)
{
    m_socket->write(msg.toStdString().c_str());
    m_socket->flush();

    if (!m_socket->bytesAvailable())
        m_socket->waitForReadyRead();

    QTextStream stream(m_socket);
    QString respond = stream.readAll();
    qDebug() << "Read Data From Server:" << respond;
}

void CClient::socketConnectedHandler()
{
    qDebug() << "connected.";
}


void CClient::socketDisConnectedHandler()
{
    qDebug() << "disconnected.";
}

void CClient::socketErrorHandler(QLocalSocket::LocalSocketError error)
{
    qWarning() << error;
}



